<?php

/**
 * класс для работы с таблицей категорий
 *
 * @author kingop
 */
class DatabaseObject_Products extends DatabaseObject {

    public $files = null;
    public $image = null;
    public $thumb = null;
    public $reviews = null;

    public function __construct($db) {
        parent::__construct($db, 'products', 'id');

        // далее перечислены все поля таблицы

        $this->add('name');
        $this->add('catId');
        $this->add('price');
        $this->add('descr');
        $this->add('material');
        $this->add('size');
        $this->add('color');
        $this->add('type');
        $this->add('userId');
        $this->add('logo');
        $this->add('nameshop');
        $this->add('date_add');
        $this->add('currency');
    }

    protected function preDelete() {
        parent::preDelete();

        // удалим файлы
        DatabaseObject_ProductsImg::DeleteProductsImg($this->getDb(), $this->getId());
        if($this->logo!='')
        if (file_exists(DatabaseObject_ProductsImg::GetUploadLogoDirectory() . $this->logo))
                unlink(DatabaseObject_ProductsImg::GetUploadLogoDirectory() . $this->logo);
        return true;
    }

    protected function postDelete() {
        parent::postDelete();

        // удалим файлы
       
        
    //    DatabaseObject_Categories::SetProductsCount($this->getDb(), $this->catId, 0);
        return true;
    }

    protected function postLoad() {
        parent::postLoad();

        // загрузим прикрпленные файлы
        $files = DatabaseObject_ProductsImg::GetProductsImg($this->getDb(), $this->getId());
       
        // загрузим прикрпленные логотип
        $this->image = DatabaseObject_ProductsImg::GetUrlDirectory() . '/' . $this->logo;
        $this->thumb = DatabaseObject_ProductsImg::GetUrlDirectory() . '/' . $this->logo;
        $this->files = $files;
        $cur = Zend_Registry::get('currency');
            if (isset(Zend_Auth::getInstance()->getIdentity()->id))
                $cur = DatabaseObject_User::GetCurrencyUser($this->getDb(), Zend_Auth::getInstance()->getIdentity()->id);
            else 
                $cur = 1;
             $this->price = CustomControllerAction::currency($this->price, $this->currency, $cur);
        //$this->price = CustomControllerAction::currency($this->price, $this->currency, DatabaseObject_User::GetCurrencyUser($this->getDb(), Zend_Auth::getInstance()->getIdentity()->id));
        return true;
    }

    public static function GetProducts($db, $options = array(), $filter = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );
        $filters = array(
            'catId' => 0,
            'userId' => 0,
            'type' => 0,
            'archive' => 2,
            'search' => ''
        );
        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        foreach ($filters as $k => $v) {
            $filter[$k] = array_key_exists($k, $filter) ? $filter[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'p.*');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'])
            $select->where($options['where']);

        if ($filter['userId'] != 0)
            $select->where('userId = ?', $filter['userId']);
        if ($filter['type'] != 0)
            $select->where('type = ?', $filter['type']);
        if ($filter['catId'] != 0) {
            $cat = DatabaseObject_Categories::GetChildId($db, $filter['catId']);
            $cat = implode(',', $cat);
            $select->where('catId in (' . $cat . ')');
        }
        if (strpos($options['order'], 'price') !== false) {
            if (stripos($options['order'], 'asc') !== false)
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) ASC";
            else
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) DESC";
        }
        $select->order($options['order']);

        // получим данные из базы
        $data = $db->fetchAll($select);

        foreach ($data as $k => $v) {
            if (isset(Zend_Auth::getInstance()->getIdentity()->id))
                $cur = DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id);
            else 
                $cur = 1;
            $data[$k]['price'] = CustomControllerAction::currency($v['price'], $v['currency'], $cur);
        }
        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);

        $cat_ids = array_keys($cats);

        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }

    /// Paginator
    public static function GetProductsCount($db, $options = array(), $filter = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );
        $filters = array(
            'catId' => 0,
            'userId' => 0,
            'archive' => 2,
            'type' => 0,
            'search' => ''
        );
        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        foreach ($filters as $k => $v) {
            $filter[$k] = array_key_exists($k, $filter) ? $filter[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'count(*)');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'])
            $select->where($options['where']);
       if ($filter['userId'] != 0)
            $select->where('userId = ?', $filter['userId']);
        if ($filter['type'] != 0)
            $select->where('type = ?', $filter['type']);
        if (isset($filter['catId']) && $filter['catId'] != 0) {
            $cat=array();
            $cat = DatabaseObject_Categories::GetChildId($db, $filter['catId']);
          
            $cat = implode(',', $cat);
          
            $select->where('catId in (' . $cat . ')');
        }
        $select->order($options['order']);
     //echo $select->__toString();
        return $db->fetchOne($select);
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('p' => 'products'), array());

        return $select;
    }

    /// Получение количество всех товаров
    public static function GetCount($db) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        return $db->fetchOne($select);
    }

    /// Получение количество товаров у пользователя
    public static function GetCountUser($db, $userId, $cat = false, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        $select->where('userId = ?', $userId);
        if ($cat)
            $select->where('catId = ?', $cat);
        if ($type)
            $select->where('type = ?', $type);

        return $db->fetchOne($select);
    }

    /// Получение информации о товаре 
    public static function GetShopProduct($db, $productId, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'p.*');
        $select->where('id = ?', $productId);
        if ($type)
            $select->where('type = ?', $type);
        $data = $db->fetchAll($select);
        foreach ($data as $k => $v) {
            $data[$k][price] = CustomControllerAction::currency($v[price], $v[currency], DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id));
        }
        return self::BuildMultiple($db, __CLASS__, $data);
    }

    /// Получение список товаров пользователя
    public static function GetUserProduct($db, $userId, $cat = false, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'p.*');
        $select->where('userId = ?', $userId);
        if ($cat)
            $select->where('catId = ?', $cat);
        if ($type)
            $select->where('type = ?', $type);
        $data = $db->fetchAll($select);
        foreach ($data as $k => $v) {
            $data[$k][price] = CustomControllerAction::currency($v[price], $v[currency], DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id));
        }
        return self::BuildMultiple($db, __CLASS__, $data);
    }

    /// Получение список категорий где есть товары пользователя
    public static function GetCatProduct($db, $userId, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->distinct();
        $select->from(null, 'p.catId');
        $select->where('userId = ?', $userId);
        if ($type)
            $select->where('type = ?', $type);
        $data = $db->fetchAll($select);
        foreach ($data as $k => $v) {
            $catid = $v['catId'];
            $cat = new DatabaseObject_Categories($db);
            $cat->load($catid);
            if ($cat->level=='3') {
                $cat1 = new DatabaseObject_Categories($db);
                $cat1->load($cat->parent_id);
               $c =DatabaseObject_Products::GetUserProductCount($db,  $userId, $cat1->getId());
                  $cat1->count = $c;
                if(!in_array($cat1,$cats)) {
              
                    $cats[] = $cat1;
                  
                }
            }else{
               $c1 = DatabaseObject_Products::GetUserProductCount($db, $userId, $catid);
               $cat->count = $c1;
                
                $cats[] = $cat;
           }
        }
      
     //   CustomControllerAction::pre($cats);
        return $cats;
    }

    /// Получение список часто продаваемых товаров 
    public static function GetTopProduct($db, $cat = false, $type = false) {
        // $top = DatabaseObject_Orders::GetBasket($db, array('limit' => '8'));
        $top = $db->fetchAll("SELECT DISTINCT product_id FROM `order_products` LIMIT 8");
        // CustomControllerAction::pre($top);
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'p.*');
        foreach ($top as $val) {
            //$val['product_id'];
            $select->orWhere('id = ?', $val['product_id']);
        }
        if ($cat)
            $select->where('catId = ?', $cat);
        if ($type)
            $select->where('type = ?', $type);
        // echo $select->__toString();
        $data = $db->fetchAll($select);
        // print_r($data);
        foreach ($data as $k => $v) {
             if (isset(Zend_Auth::getInstance()->getIdentity()->id))
                $cur = DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id);
            else 
                $cur = 1;
            $data[$k]['price'] = CustomControllerAction::currency($v['price'], $v['currency'], $cur);
        }
        return self::BuildMultiple($db, __CLASS__, $data);
    }

    ////////////////////////////////////////////
    //////////Поиск///////////////////////////// 
    ////////////////////////////////////////////
    public static function GetSearchProducts($db, $options = array(), $filter = array()) {
        // инициализируем настройки
        $defaults = array(
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );

        $filters = array(
            'catId' => 0,
            'search' => '',
            'material' => 0,
            'tags' => 0,
            'type' => ''
        );
        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        foreach ($filters as $k => $v) {
            $filter[$k] = array_key_exists($k, $filter) ? $filter[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'p.*');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);


        $sql='';
        if ($filter['catId'] != 0) {
            $cat = DatabaseObject_Categories::GetChildId($db, $filter['catId']);
            $cat = implode(',', $cat);
            $select->where('catId in (' . $cat . ')');
        }
        if ($filter['type'] != 0)
            $select->where('type = ?', $filter['type']);
        if ($filter['search'] != '') {
            $i = 0;
            foreach ($filter['search'] as $key => $value) {
                $i++;
                $sql = $sql . " `name` LIKE '%" . $value . "%' OR  `color` LIKE '%" . $value . "%'" . ($i == count($filter['search']) ? "" : " OR");
            }
        }

        if (count($filter['material']) > 0 && $filter['material']!=0) {
            if ($filter['search'] != '') {
                $sql = $sql . ' AND ';
            }
            $k = 0;
            foreach ($filter['material'] as $key => $value) {
                $k++;
                $sql = $sql . " `material` LIKE '%" . $value . "%'" . ($k == count($filter['material']) ? "" : " OR");
            }
        }
        if (count($filter['tags']) > 0 && $filter['tags']!=0) {
            if ($filter['search'] != '' || $filter['material'] != '') {
                $sql = $sql . ' AND ';
            }
            $l = 0;
            foreach ($filter['tags'] as $key => $value) {
                $l++;
                $sql = $sql . " `color` LIKE '%" . $value . "%'" . ($l == count($filter['tags']) ? "" : " OR");
            }
        }
       // echo count($filter['tags']);
        if ($sql!='')
            $select->where($sql);
          if (strpos($options['order'], 'price') !== false) {
            if (stripos($options['order'], 'asc') !== false)
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) ASC";
            else
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) DESC";
        }
        $select->order($options['order']);
        $data = $db->fetchAll($select);

        foreach ($data as $k => $v) {
               if (isset(Zend_Auth::getInstance()->getIdentity()->id))
                $cur = DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id);
            else 
                $cur = 1;
            $data[$k]['price'] = CustomControllerAction::currency($v['price'], $v['currency'], $cur);
            
        }
        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);

        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }
     public static function GetSearchProductsCount($db, $options = array(), $filter = array()) {
        // инициализируем настройки
        $defaults = array(
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );

        $filters = array(
            'catId' => 0,
            'search' => '',
            'material' => 0,
            'tags' => 0,
            'type' => ''
        );
        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        foreach ($filters as $k => $v) {
            $filter[$k] = array_key_exists($k, $filter) ? $filter[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'count(*)');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);


        $sql='';
        if ($filter['catId'] != 0) {
            $cat = DatabaseObject_Categories::GetChildId($db, $filter['catId']);
            $cat = implode(',', $cat);
            $select->where('catId in (' . $cat . ')');
        }
        if ($filter['type'] != 0)
            $select->where('type = ?', $filter['type']);
        if ($filter['search'] != '') {
            $i = 0;
            foreach ($filter['search'] as $key => $value) {
                $i++;
                $sql = $sql . " `name` LIKE '%" . $value . "%' OR  `color` LIKE '%" . $value . "%'" . ($i == count($filter['search']) ? "" : " OR");
            }
        }

        if (count($filter['material']) > 0 && $filter['material']!=0) {
            if ($filter['search'] != '') {
                $sql = $sql . ' AND ';
            }
            $k = 0;
            foreach ($filter['material'] as $key => $value) {
                $k++;
                $sql = $sql . " `material` LIKE '%" . $value . "%'" . ($k == count($filter['material']) ? "" : " OR");
            }
        }
        if (count($filter['tags']) > 0 && $filter['tags']!=0) {
            if ($filter['search'] != '' || $filter['material'] != '') {
                $sql = $sql . ' AND ';
            }
            $l = 0;
            foreach ($filter['tags'] as $key => $value) {
                $l++;
                $sql = $sql . " `color` LIKE '%" . $value . "%'" . ($l == count($filter['tags']) ? "" : " OR");
            }
        }
       // echo count($filter['tags']);
        if ($sql!='')
            $select->where($sql);
          if (strpos($options['order'], 'price') !== false) {
            if (stripos($options['order'], 'asc') !== false)
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) ASC";
            else
                $options['order'] = "p.price*(SELECT value FROM currency WHERE currency.id = p.currency) DESC";
        }
        $select->order($options['order']);
        $data = $db->fetchOne($select);

    
        // сделаем из полученных записей объекты класса
       

        return $data;
    }

    public static function GetProductsTags($db, $options = array(), $filter = array()) {
        // инициализируем настройки
        $filters = array(
            'catId' => 0,
            'userId' => 0,
            'type' => 0,
            'archive' => 2,
            'search' => ''
        );

        foreach ($filters as $k => $v) {
            $filter[$k] = array_key_exists($k, $filter) ? $filter[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, array('material', 'color'));

        // зададим настройки

        if ($filter['userId'] != 0)
            $select->where('userId = ?', $filter['userId']);
        if ($filter['type'] != 0)
            $select->where('type = ?', $filter['type']);
        if ($filter['catId'] != 0) {
            $cat = DatabaseObject_Categories::GetChildId($db, $filter['catId']);
            $cat = implode(',', $cat);
            $select->where('catId in (' . $cat . ')');
        }
$material = ''; $color='';
        // получим данные из базы
        $data = $db->fetchAll($select);

        foreach ($data as $k => $v) {
            if(isset($v['material']))
            $material .= $v['material'] . ',';
            if(isset($v['color']))
            $color .= $v['color'] . ',';
        }
        if ($material)
        $material = explode(',', trim($material, ','));
         if ($color)
        $color = explode(',', trim($color, ','));
 if ($material)
        $tags['material'] = array_keys(array_count_values($material)); // CustomControllerAction::getCountTags($material,$temp);
if ($color)
        $tags['color'] = array_keys(array_count_values($color)); // CustomControllerAction::getCountTags($color,$temp);
        $cat_ids = array_keys($tags);

        if (count($cat_ids) == 0)
            return array();

        return $tags;
    }

    // uasort – сортирует массив, используя пользовательскую функцию mySort
    
     /// Получение количество товаров пользователя 
    public static function GetUserProductCount($db, $userId=false, $cat = false, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        if ($userId)
        $select->where('userId = ?', $userId);
        if ($cat){
            $cat1 = DatabaseObject_Categories::GetChildId($db, $cat);
             // CustomControllerAction::pre($cat1);
            $cat2 = implode(',', $cat1);
            $select->where('catId in (' . $cat2 . ')');    
       // $select->where('catId = ?', $cat);
        
        }
    
        if ($type)
            $select->where('type = ?', $type);
     
        $data = $db->fetchOne($select);
       /* foreach ($data as $k => $v) {
            $data[$k][price] = CustomControllerAction::currency($v[price], $v[currency], DatabaseObject_User::GetCurrencyUser($db, Zend_Auth::getInstance()->getIdentity()->id));
        }*/
        return $data;
    }

}

?>
